using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SumerCoreDevOps.Application.Statistics.Queries;
using SumerCoreDevOps.Shared.Models;

namespace SumerCoreDevOps.ControlApi.Controllers;

/// <summary>
/// 统计数据接口
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class StatisticsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<StatisticsController> _logger;

    public StatisticsController(IMediator mediator, ILogger<StatisticsController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// 获取Dashboard统计数据
    /// </summary>
    /// <returns>返回Dashboard统计数据对象,包括今日构建总数、构建成功率、平均构建时间、活跃节点数等关键指标;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回Dashboard统计数据</response>
    [HttpGet("dashboard")]
    [ProducesResponseType(typeof(ApiResponse<DashboardStatistics>), 200)]
    public async Task<IActionResult> GetDashboardStatistics()
    {
        var stats = await _mediator.Send(new GetDashboardStatisticsQuery());
        return Ok(ApiResponse.Ok(stats));
    }

    /// <summary>
    /// 获取构建趋势数据
    /// </summary>
    /// <param name="days">统计天数，默认7天</param>
    /// <returns>返回指定天数内的构建趋势数据列表,每天包含日期、总构建数、成功数、失败数等信息,用于绘制趋势图表;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回构建趋势数据</response>
    [HttpGet("build-trend")]
    [ProducesResponseType(typeof(ApiResponse<List<BuildTrendData>>), 200)]
    public async Task<IActionResult> GetBuildTrend([FromQuery] int days = 7)
    {
        var trendData = await _mediator.Send(new GetBuildTrendQuery(days));
        return Ok(ApiResponse.Ok(trendData));
    }

    /// <summary>
    /// 获取任务状态分布
    /// </summary>
    /// <returns>返回任务状态分布统计对象,包含各状态(运行中、成功、失败、等待中等)的任务数量统计,用于绘制饼图或柱状图;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回任务状态分布数据</response>
    [HttpGet("task-status-distribution")]
    [ProducesResponseType(typeof(ApiResponse<TaskStatusDistribution>), 200)]
    public async Task<IActionResult> GetTaskStatusDistribution()
    {
        var distribution = await _mediator.Send(new GetTaskStatusDistributionQuery());
        return Ok(ApiResponse.Ok(distribution));
    }
}
